package com.atguigu.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Date;


@Component
@Data
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class AliyunOSSUtils {


    private  String endPoint;
    private  String keyId;
    private  String keySecret;
    private  String bucketName;




    public  String uploadImage(String objectName, byte[] content,String contentType,int hours)  throws Exception {

        OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);

        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content), objectMetadata);

        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 300 * hours);

        String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();

        ossClient.shutdown();
        return url;
    }


    public  void downFile(String objectName,
                                String localFile) throws Exception {

        OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);


        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFile));


        ossClient.shutdown();
    }


    public  void deleteFile(String objectName) {

        OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);

        ossClient.deleteObject(bucketName, objectName);


        ossClient.shutdown();
    }

}
